<?php
namespace app\api\controller;

use app\api\model\Wx;
use app\common\controller\Api;
use app\common\library\Sms;
use think\Cache;
use \app\admin\model\Signin;
use \app\admin\model\Volunteer;
use \app\admin\model\VolunteerAudit;
use \app\manystore\model\Goods as GoodsModel;

/**
 * 首页接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function logintest($value = '')
    {
        $u       = input('u', 'admin');
        $p       = input('p', '123456');
        $vmodel  = new Volunteer;
        $smodel  = new Signin;
        $vamodel = new VolunteerAudit;

        $status    = $this->auth->login($u, $p);
        $user_info = $this->auth->getUserinfo();

        $user = ['avatar' => $user_info['avatar'], 'nickname' => $user_info['nickname'], 'user_type' => 1, 'level' => $user_info['level_name'], 'region' => '', 'score' => $user_info['score'], 'collection_num' => 0, 'workinghours' => $user_info['workinghours'], 'interface_style' => $user_info['interface_style'], 'province' => $user_info['province'], 'city' => $user_info['city'], 'district' => $user_info['district'], 'area_one_id' => 0, 'area_tow_id' => 0, 'token' => $user_info['token']];

        if (! $user['level']) {
            $user['level'] = db('volunteer_level')->order('id asc')->value('name');
        }

        $user['collection_num'] = db('collection')
            ->where(['user_id' => $this->auth->id, 'type' => ['neq', 6]])
            ->count();

        $where       = ['c.user_id' => $this->auth->id, 'c.type' => '6', 'g.goods_status' => '10'];
        $model       = new GoodsModel;
        $goods_total = $model
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->count();

        $user['collection_num'] += $goods_total;

        $volunteer = $vmodel
            ->where(['user_id' => $this->auth->id])
            ->find();

        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $volunteer_audit_status = 0;

        $volunteer_audit = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        if ($volunteer_audit) {
            $volunteer_audit_status = $volunteer_audit['status'];
        }

        // 審核通過，但是把義工身份刪除了
        if (isset($volunteer_audit) && $volunteer_audit['status'] == 2 && ! $volunteer) {
            $volunteer_audit_status = 0;
        }

        if ($volunteer) {
            $volunteer_audit_status = 2;
            $user['user_type']      = 2;
            $region_address         = db('area')
                ->where(['id' => $volunteer['area_one_id']])
                ->value('name');

            $city = db('area')
                ->where(['id' => $volunteer['area_tow_id']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
            }
            $user['region']      = $region_address ? $region_address : '';
            $user['area_one_id'] = $volunteer['area_one_id'];
            $user['area_tow_id'] = $volunteer['area_tow_id'];
        }

        $user['volunteer_audit_status'] = $volunteer_audit_status;
        $user['signin_status']          = $smodel
            ->where('user_id', $this->auth->id)
            ->whereTime('createtime', 'today')
            ->count();

        $this->success('请求成功', $user);

    }

    /*
    *获取小程序的session_key
    */
    public function getSessionKey($value = '')
    {
        $code    = input('code');
        $Wx      = new Wx();
        $package = $Wx->getSessionKey($code);
        if (isset($package['errcode']) && $package['errcode'] != 0) {
            $this->error('系統繁忙');
        }
        //获取成功，颁发令牌
        $openid      = $package['openid'];
        $session_key = $package['session_key'];
        Cache::set($session_key, $openid, 864000);
        $this->success('请求成功', $session_key);
    }

    /**
     * [getWxMobile 解密微信手机号]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-11-02T15:02:07+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getWxMobile($value = '')
    {
        $session_key = input('post.session_key', '');
        // 微信用户(电话信息)
        $encryptedData = input('post.encryptedData', '');
        $iv            = input('post.iv', '');
        $Wx            = new Wx();
        $decryptedData = $Wx->decryptedData($session_key, $iv, $encryptedData);
        // print_r($decryptedData);exit;
        if (! isset($decryptedData['phoneNumber'])) {
            $this->error('系統繁忙');
        }
        $data = [];

        //获取成功
        //用户绑定的手机号（国外手机号会有区号）
        $data['phoneNumber'] = $decryptedData['phoneNumber'];
        // 没有区号的手机号
        $data['purePhoneNumber'] = $decryptedData['purePhoneNumber'];
        // 区号
        $data['countryCode'] = $decryptedData['countryCode'];

        $user = $this->login_wxapp($encryptedData, $iv, $session_key, $data['phoneNumber'], $data['countryCode'],$decryptedData['purePhoneNumber']);

        if ($user['code'] != 200) {
            $this->error($user['msg'] ? $user['msg'] : '登录失败', []);
        }

        $vmodel  = new Volunteer;
        $smodel  = new Signin;
        $vamodel = new VolunteerAudit;

        $user_info = $this->auth->getUserinfo();

        $user = ['avatar' => $user_info['avatar'], 'nickname' => $user_info['nickname'], 'user_type' => 1, 'level' => $user_info['level_name'], 'region' => '', 'score' => $user_info['score'], 'collection_num' => 0, 'workinghours' => $user_info['workinghours'], 'interface_style' => $user_info['interface_style'], 'province' => $user_info['province'], 'city' => $user_info['city'], 'district' => $user_info['district'], 'area_one_id' => 0, 'area_tow_id' => 0, 'token' => $user_info['token']];

        if (! $user['level']) {
            $user['level'] = db('volunteer_level')->order('id asc')->value('name');
        }

        $user['collection_num'] = db('collection')
            ->where(['user_id' => $this->auth->id, 'type' => ['neq', 6]])
            ->count();

        $where       = ['c.user_id' => $this->auth->id, 'c.type' => '6', 'g.goods_status' => '10'];
        $model       = new GoodsModel;
        $goods_total = $model
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->count();

        $user['collection_num'] += $goods_total;

        $volunteer = $vmodel
            ->where(['user_id' => $this->auth->id])
            ->find();

        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $volunteer_audit_status = 0;

        $volunteer_audit = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        if ($volunteer_audit) {
            $volunteer_audit_status = $volunteer_audit['status'];
        }

        // 審核通過，但是把義工身份刪除了
        if (isset($volunteer_audit) && $volunteer_audit['status'] == 2 && ! $volunteer) {
            $volunteer_audit_status = 0;
        }

        if ($volunteer) {
            $volunteer_audit_status = 2;
            $user['user_type']      = 2;
            $region_address         = db('area')
                ->where(['id' => $volunteer['area_one_id']])
                ->value('name');

            $city = db('area')
                ->where(['id' => $volunteer['area_tow_id']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
            }
            $user['region']      = $region_address ? $region_address : '';
            $user['area_one_id'] = $volunteer['area_one_id'];
            $user['area_tow_id'] = $volunteer['area_tow_id'];
        }

        $user['volunteer_audit_status'] = $volunteer_audit_status;
        $user['signin_status']          = $smodel
            ->where('user_id', $this->auth->id)
            ->whereTime('createtime', 'today')
            ->count();

        $this->success('登录成功', $user);

        // $this->success('请求成功', $data);
    }

    /**
     * 用户登录
     */
    public function login()
    {
        // 微信用户小程序(用户信息)
        $session_key   = input('post.session_key', '');
        $encryptedData = input('post.encryptedData', '');
        $iv            = input('post.iv', '');
        $mobile        = input('post.mobile', '');
        $countryCode   = input('post.countryCode', '');
        $captcha       = input('post.captcha', '');
        if (! $mobile) {
            $this->error('請填寫手機號碼');
        }

        if (! $captcha) {
            $this->error('請填寫驗證碼');
        }

        $mobile = preg_replace('# #', '', $mobile);

        // $result = true;
        // if ( $captcha != '1234' ) {
        //   $result = false;
        // }
        $result = Sms::check($mobile, $captcha, 'mobilelogin');
        if ($captcha != '145987') {
            if (! $result) {
                $this->error('驗證碼不正確');
            }
        }

        Sms::flush($mobile, 'mobilelogin');

        $user = $this->login_wxapp($encryptedData, $iv, $session_key, $mobile, $countryCode);

        if ($user['code'] != 200) {
            $this->error($user['msg'] ? $user['msg'] : '登录失败', []);
        }

        $vmodel  = new Volunteer;
        $smodel  = new Signin;
        $vamodel = new VolunteerAudit;

        $user_info = $this->auth->getUserinfo();

        $user = ['avatar' => $user_info['avatar'], 'nickname' => $user_info['nickname'], 'user_type' => 1, 'level' => $user_info['level_name'], 'region' => '', 'score' => $user_info['score'], 'collection_num' => 0, 'workinghours' => $user_info['workinghours'], 'interface_style' => $user_info['interface_style'], 'province' => $user_info['province'], 'city' => $user_info['city'], 'district' => $user_info['district'], 'area_one_id' => 0, 'area_tow_id' => 0, 'token' => $user_info['token']];

        if (! $user['level']) {
            $user['level'] = db('volunteer_level')->order('id asc')->value('name');
        }

        $user['collection_num'] = db('collection')
            ->where(['user_id' => $this->auth->id, 'type' => ['neq', 6]])
            ->count();

        $where       = ['c.user_id' => $this->auth->id, 'c.type' => '6', 'g.goods_status' => '10'];
        $model       = new GoodsModel;
        $goods_total = $model
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->count();

        $user['collection_num'] += $goods_total;

        $volunteer = $vmodel
            ->where(['user_id' => $this->auth->id])
            ->find();

        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $volunteer_audit_status = 0;

        $volunteer_audit = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        if ($volunteer_audit) {
            $volunteer_audit_status = $volunteer_audit['status'];
        }

        // 審核通過，但是把義工身份刪除了
        if (isset($volunteer_audit) && $volunteer_audit['status'] == 2 && ! $volunteer) {
            $volunteer_audit_status = 0;
        }

        if ($volunteer) {
            $volunteer_audit_status = 2;
            $user['user_type']      = 2;
            $region_address         = db('area')
                ->where(['id' => $volunteer['area_one_id']])
                ->value('name');

            $city = db('area')
                ->where(['id' => $volunteer['area_tow_id']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
            }
            $user['region']      = $region_address ? $region_address : '';
            $user['area_one_id'] = $volunteer['area_one_id'];
            $user['area_tow_id'] = $volunteer['area_tow_id'];
        }

        $user['volunteer_audit_status'] = $volunteer_audit_status;
        $user['signin_status']          = $smodel
            ->where('user_id', $this->auth->id)
            ->whereTime('createtime', 'today')
            ->count();

        $this->success('登录成功', $user);
    }

    /*
    *微信小程序登录
     */
    public function login_wxapp($encryptedData, $iv, $session_key, $mobile, $countryCode,$purePhoneNumber='')
    {
        $data['code'] = 200;
        $data['data'] = [];
        $data['msg']  = '请求成功';

        $open_id = Cache::get($session_key);
        if (! $open_id) {
            $data['code'] = 201;
            $data['msg']  = '系统繁忙1';
            return $data;
        }
        $login_status = $this->auth->loginM($mobile);
        if ($login_status['code'] == '201') {
            $data['code'] = 201;
            $data['msg']  = $this->auth->getError() ?: '系統繁忙2';
            return $data;
        }

        if ($login_status['code'] == '200') {
            return $data;
        }

        $Wx            = new Wx();
        $decryptedData = $Wx->decryptedData($session_key, $iv, $encryptedData);
        // if (! isset($decryptedData['nickName'])) {
        //     $data['code'] = 201;
        //     $data['msg']  = '系统繁忙3';
        //     return $data;
        // }
        $map['nickname']    = $purePhoneNumber;
        $map['avatar']      = '';
        $map['gender']      = '';
        $map['mobile']      = $mobile;
        $map['countryCode'] = $countryCode;

        $third             = [];
        $third['platform'] = '微信小程序';
        $third['apptype']  = 'miniapp';
        // $third['unionid'] = $datas['unionId'];
        $third['openname'] = $purePhoneNumber;
        $third['openid']   = $open_id;
        $login_status      = $this->auth->registerN('wechatapp', $map, $third);
        if (! $login_status) {
            $data['code'] = 201;
            $data['msg']  = $this->auth->getError() ?: '系統繁忙';
        }
        return $data;
    }
}
